package com.banner.lyl.controller;
import com.banner.lyl.IUserService;
import com.banner.lyl.entity.User;
import com.banner.lyl.service.impl.UserServiceImpl;
import com.banner.lyl.utils.JavaDateConnection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author: Re
 * @Date: 2021/3/23 19:22
 */
@WebServlet("/insertUser")
public class InsertUserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 防止乱码
        response.setContentType("text/html;charset=UTF-8");
        // 获取表单内容
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");

        // 判断表单内容是否为空
        if (userName == null || "".equals(userName.trim())) {
            request.setAttribute("msg","用户名不能为空");
            request.getRequestDispatcher("index.jsp").forward(request,response);
            return;
        }
        if (userPassword == null || "".equals(userPassword.trim())) {
            request.setAttribute("msg","密码不能为空");
            request.getRequestDispatcher("index.jsp").forward(request,response);
            return;
        }
        // 封装成一个对象
        User user = new User(userName,userPassword);
        IUserService iUserService= new UserServiceImpl();
        boolean judgment = iUserService.insertUser(user);
        if(judgment){
            JavaDateConnection javaDateConnection = new JavaDateConnection();
            PreparedStatement preparedStatement = null;
            Connection connection = null;
            try {
                connection = javaDateConnection.getConn();
                String sql = "insert into userTest(userName,userPassword) value(?,?)";
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1,userName);
                preparedStatement.setString(2,userPassword);
                int count = preparedStatement.executeUpdate();
                if (count == 1) {
                    request.setAttribute("msg","注册成功");
                    request.getRequestDispatcher("index.jsp").forward(request,response);
                } else {
                    request.setAttribute("msg", "注册失败，请稍后重试");
                    request.getRequestDispatcher("index.jsp").forward(request, response);
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                JavaDateConnection.closeConnection(connection,preparedStatement,null);
            }
        }
    }
}
